<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once BASE_PATH.'application/models/app_model.php';

/*
	Model: Login
	

*/


class Login_model extends APP_Model {

	protected $binding = 'login';

	function init() {
		$this->load->library('session');
		$this->load->helper('security');
		$this->load->library('form_validation');
		$this->load->database();
		$this->load->model('User_model', 'user');
		$uid = $this->session->userdata('uid');
		if($uid){
			$this->uid = $uid;
		}else{
			$this->uid = false;
		}
    }
	
	private $uid;
	
	public function email_in_db($email){
		$user = $this->user->find_by_email($email);
		if($user === false){
			return false;
		}else{
			$this->id = $user['id'];
			return true;
		}
	}
	
	public function match_password($password){
		$user_password = $this->user->get_password($this->id);
		if(do_hash($password) == $user_password){
			return true;
		}else{
			return false;
		}
	}
	
	
	
	public function login($email, $password){
		$data = array('email'=>$email, 'password'=>$password);
		$this->validate( $data );
		if($this->isValid){
			$this->uid = $this->id;
			$this->session->set_userdata('uid', $this->uid);
			return true;
		}else{
			return false;
		}
	}
	
	public function logout(){
		$this->session->unset_userdata('uid');
		$this->uid = false;
	}
	
	public function current_user(){
		if( $this->uid === false ){
			return false;
		}else{
			$user = $this->user->find_by_id($this->uid);
			return $user;
		}
		
	}
	
	public function is_logged_in(){
		if($this->uid !== false){
			return true;
		}else{
			return false;
		}
	}
	
	public function is_admin(){
		$user = $this->current_user();
		if($user === false){
			return false;
		}else{
			if($user['user_type_id'] == 2){
				return true;
			}else{
				return false;
			}
		}
	}
	
	

}
